package com.le.buddha.websocket;


import cn.hutool.json.JSONUtil;
import com.le.buddha.common.ApplicationContextHolder;
import com.le.buddha.common.SocketResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint(value = "/websocket/{oid}")
@Component
@Slf4j
public class WebSocketSever {


    // 与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    // session集合,存放对应的session
    private static ConcurrentHashMap<String, Session> sessionPool = new ConcurrentHashMap<>();

    // concurrent包的线程安全Set,用来存放每个客户端对应的WebSocket对象。
    private static CopyOnWriteArraySet<WebSocketSever> webSocketSet = new CopyOnWriteArraySet<>();

    /**
     * 建立WebSocket连接
     *
     * @param session
      */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "oid") String oid) {
        log.info("WebSocket建立连接中,连接用户openId：{}", oid);
        // 建立连接
        this.session = session;
        webSocketSet.add(this);

        sessionPool.put(oid, session);
        ApplicationContextHolder.getBean(OpenHandle.class).handle(oid);

        log.info("建立连接完成,当前在线人数为：{}", webSocketSet.size());
    }

    /**
     * 发生错误
     *
     * @param throwable e
     */
    @OnError
    public void onError(Throwable throwable) {
        throwable.printStackTrace();
    }

    /**
     * 连接关闭
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        String oid=  session.getPathParameters().get("oid");
        ApplicationContextHolder.getBean(CloseHandle.class).handle(oid);
        log.info("连接断开,当前在线人数为：{}", webSocketSet.size());
    }

    /**
     * 接收客户端消息
     *
     * @param message 接收的消息
     */
    @OnMessage
    public void onMessage(String message,@PathParam(value = "oid") String oid ) {



        ApplicationContextHolder.getBean(MessageHandle.class).handle(oid, message);


    }

    /**
     * 推送消息到指定用户
     *

     */
    public static void sendMessageByUser(String oid, String message,Integer messageType) {
         Session session = sessionPool.get(oid);
        try {
            String response=JSONUtil.toJsonStr(SocketResponse.success(message,messageType));
           log.info("sendMessageByUser"+response);
            session.getBasicRemote().sendText(response);
        } catch ( Exception e) {
            log.error("推送消息到指定用户发生错误：" + e.getMessage(), e);
        }
    }

    /**
     * 推送消息到指定用户
     *

     */
    public static void sendMessageByUser(String oid, byte[] message) {
         Session session = sessionPool.get(oid);
        try {
            //   String response=JSON.toJSONString(message);
            session.getBasicRemote().sendBinary(ByteBuffer.wrap(message));
        } catch ( Exception e) {
            log.error("推送消息到指定用户发生错误：" + e.getMessage(), e);
        }
    }
    /**
     * 群发消息
     *
     * @param message 发送的消息
     */
    public static void sendAllMessage(String message) {
         for (WebSocketSever webSocket : webSocketSet) {
            try {
                webSocket.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                log.error("群发消息发生错误：" + e.getMessage(), e);
            }
        }
    }

}

